

const path = require('path');
const fs = require('fs');

// 获取 多少行
// http://stackoverflow.com/questions/11386492/accessing-line-number-in-v8-javascript-chrome-node-js
Object.defineProperty(global, '__stack', {
    get: function(){
        var orig = Error.prepareStackTrace;
        Error.prepareStackTrace = function(_, stack){ return stack; };
        var err = new Error;
        Error.captureStackTrace(err, arguments.callee);
        var stack = err.stack;
        Error.prepareStackTrace = orig;
        return stack;
    }
});

Object.defineProperty(global, '__line', {
    get: function(){
        return __stack[1].getLineNumber();
    }
});

function getDayStamp() {
    let now = new Date();
    let y = now.getFullYear();
    let m = now.getMonth() + 1;
    let d = now.getDate();
    return `${y}-${m}-${d}`;
}

function getCurFormatTime(){
    let now = new Date();
    let y = now.getFullYear();

    let m = now.getMonth() + 1;
    if(m < 10){
        m = '0' + m;
    }

    let d = now.getDate();
    if(d < 10){
        d = '0' + d;
    }

    let h = now.getHours();
    if(h < 10){
        h = '0' + h
    }

    let min = now.getMinutes();
    if(min < 10){
        min = '0' + min;
    }

    let sec = now.getSeconds();
    if(sec < 10){
        sec = '0' + sec;
    }
    return `${y}-${m}-${d} ${h}:${min}:${sec}`;
}

//
let logUtils = {
    dayTime:null,
    infoFile:null,
    errFile:null,
    debug:true,

    _writeTo(file,msg){
        if(this.debug){
            console.log(msg);
        }
        fs.appendFile(file,msg,err=>{
            if(err){
                throw err;
            }
        });
    },

    info(msg){
        this.checkNewDay();
        this._writeTo(this.infoFile,msg);
    },
    err(msg){
        this.checkNewDay();
        this._writeTo(this.errFile,msg);
    },
    checkNewDay(){
        let curStamp = getDayStamp();
        let bNewDay = this.dayTime !== curStamp;
        if(bNewDay){
            this.dayTime = curStamp;
            this.infoFile = path.join(__dirname,"logs/info_" + curStamp +".log");
            this.errFile = path.join(__dirname,"logs/err_"+curStamp+".log");
        }
    },

    getLogger(filename){
        return new Logger(filename);
    }
};


class Logger{
    constructor(filename){
        this.filename = path.basename(filename);
    }
    info(){
        let msg = Array.prototype.join.call(arguments,' ');
        let formatTime = getCurFormatTime();
        logUtils.info(`${this.filename} ${formatTime} ${msg}\n`);
    }
    err(){
        let msg = Array.prototype.join.call(arguments,' ');
        let formatTime = getCurFormatTime();
        logUtils.err(`${this.filename} ${formatTime} ${msg}\n`);
    }
}


module.exports = logUtils;
